<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="渠道编号" prop="channelCode">
        <el-input v-model="formData.channelCode" placeholder="请输入渠道编号" />
      </el-form-item>
      <el-form-item label="渠道名称" prop="channelName">
        <el-input v-model="formData.channelName" placeholder="请输入渠道名称" />
      </el-form-item>
      <el-form-item label="渠道等级" prop="channelLevel">
        <el-input v-model="formData.channelLevel" placeholder="请输入渠道等级" />
      </el-form-item>
      <el-form-item label="代理人" prop="agentId">
        <el-select v-model="formData.agentId" filterable placeholder="请选择">
          <el-option
            v-for="item in agentList"
            :key="item.id"
            :label="item.agentName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="父id" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="channelInfoTree"
          :props="{ ...defaultProps, label: 'channelName' }"
          check-strictly
          default-expand-all
          placeholder="请选择父id"
        />
      </el-form-item>
      <el-form-item label="联系人名称" prop="concatName">
        <el-input v-model="formData.concatName" placeholder="请输入联系人名称" />
      </el-form-item>
      <el-form-item label="联系方式" prop="concatNumber">
        <el-input v-model="formData.concatNumber" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="地址" prop="concatAddress">
        <el-input v-model="formData.concatAddress" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item label="是否展示报告" prop="isShowReport">
        <el-input v-model="formData.isShowReport" placeholder="请输入是否展示报告" />
      </el-form-item>
      <el-form-item label="出货价" prop="shippingPrice">
        <el-input v-model="formData.shippingPrice" placeholder="请输入出货价" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ChannelInfoApi, ChannelInfo } from '@/api/health/channelinfo'
import { defaultProps, handleTree } from '@/utils/tree'
//引入代理商列表
import * as AgentInfo from '@/api/health/agentinfo'
/** 大健康渠道信息 表单 */
defineOptions({ name: 'ChannelInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const agentList = ref([] as AgentInfo.AgentInfo[])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  channelCode: undefined,
  channelName: undefined,
  channelLevel: undefined,
  agentId: undefined,
  parentId: undefined,
  concatName: undefined,
  concatNumber: undefined,
  concatAddress: undefined,
  isShowReport: undefined,
  shippingPrice: undefined
})
const formRules = reactive({
  channelName: [{ required: true, message: '渠道名称不能为空', trigger: 'blur' }],
  channelLevel: [{ required: true, message: '渠道等级不能为空', trigger: 'blur' }],
  parentId: [{ required: true, message: '父id不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const channelInfoTree = ref() // 树形结构
const getAgentUserList = async () => {
  const { list: agentUserList } = await AgentInfo.AgentInfoApi.getAgentInfoNotPage({})
  agentList.value = agentUserList
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  getAgentUserList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ChannelInfoApi.getChannelInfo(id)
    } finally {
      formLoading.value = false
    }
  }
  await getChannelInfoTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ChannelInfo
    if (formType.value === 'create') {
      await ChannelInfoApi.createChannelInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await ChannelInfoApi.updateChannelInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    channelCode: undefined,
    channelName: undefined,
    channelLevel: undefined,
    agentId: undefined,
    parentId: undefined,
    concatName: undefined,
    concatNumber: undefined,
    concatAddress: undefined,
    isShowReport: undefined,
    shippingPrice: undefined
  }
  formRef.value?.resetFields()
}

/** 获得大健康渠道信息树 */
const getChannelInfoTree = async () => {
  channelInfoTree.value = []
  const data = await ChannelInfoApi.getChannelInfoList({})
  const root: Tree = { id: 0, name: '顶级大健康渠道信息', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  channelInfoTree.value.push(root)
}
</script>
